// 检查是否在浏览器环境中
const isBrowser = typeof window !== 'undefined';

let db: any = null;
let DB_PATH = '';

// 只在Node.js环境中初始化数据库
if (!isBrowser) {
  const Database = require('better-sqlite3');
  const path = require('path');
  const fs = require('fs');

  // 数据库文件路径
  DB_PATH = path.join(process.cwd(), 'data', 'cool-red-ai.db');

  // 确保数据目录存在
  const dataDir = path.dirname(DB_PATH);
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir, { recursive: true });
  }

  // 创建数据库连接
  db = new Database(DB_PATH);
}

// 初始化数据库表
export const initDatabase = () => {
  if (isBrowser) {
    console.log('浏览器环境，跳过数据库初始化');
    return;
  }

  try {
    // 账号表 - 更新结构支持登录状态
    db.exec(`
      CREATE TABLE IF NOT EXISTS accounts (
        id TEXT PRIMARY KEY,
        username TEXT NOT NULL,
        nickname TEXT NOT NULL,
        phone TEXT,
        status TEXT DEFAULT 'inactive',
        followers INTEGER DEFAULT 0,
        following INTEGER DEFAULT 0,
        posts INTEGER DEFAULT 0,
        lastLogin TEXT,
        cookies TEXT,
        token TEXT,
        isCurrent INTEGER DEFAULT 0,
        createdAt TEXT NOT NULL,
        updatedAt TEXT NOT NULL
      )
    `);

    // 竞品账号表
    db.exec(`
      CREATE TABLE IF NOT EXISTS competitors (
        id TEXT PRIMARY KEY,
        username TEXT NOT NULL,
        nickname TEXT NOT NULL,
        avatar TEXT,
        followers INTEGER DEFAULT 0,
        following INTEGER DEFAULT 0,
        posts INTEGER DEFAULT 0,
        likes INTEGER DEFAULT 0,
        comments INTEGER DEFAULT 0,
        shares INTEGER DEFAULT 0,
        engagementRate REAL DEFAULT 0,
        category TEXT,
        lastUpdated TEXT,
        status TEXT DEFAULT 'tracking',
        createdAt TEXT NOT NULL
      )
    `);

    // 素材表
    db.exec(`
      CREATE TABLE IF NOT EXISTS materials (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        type TEXT NOT NULL,
        category TEXT NOT NULL,
        size INTEGER,
        path TEXT NOT NULL,
        tags TEXT,
        uploadTime TEXT NOT NULL,
        createdAt TEXT NOT NULL
      )
    `);

    // 草稿表
    db.exec(`
      CREATE TABLE IF NOT EXISTS drafts (
        id TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        content TEXT,
        images TEXT,
        status TEXT DEFAULT 'draft',
        createTime TEXT NOT NULL,
        updateTime TEXT NOT NULL
      )
    `);

    // 发布任务表
    db.exec(`
      CREATE TABLE IF NOT EXISTS publish_tasks (
        id TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        content TEXT,
        images TEXT,
        account TEXT NOT NULL,
        scheduledTime TEXT NOT NULL,
        status TEXT DEFAULT 'pending',
        progress INTEGER DEFAULT 0,
        retryCount INTEGER DEFAULT 0,
        maxRetries INTEGER DEFAULT 3,
        createTime TEXT NOT NULL,
        updateTime TEXT NOT NULL
      )
    `);

    // 系统设置表
    db.exec(`
      CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL,
        updatedAt TEXT NOT NULL
      )
    `);

    // 代理配置表
    db.exec(`
      CREATE TABLE IF NOT EXISTS proxies (
        id TEXT PRIMARY KEY,
        host TEXT NOT NULL,
        port INTEGER NOT NULL,
        username TEXT,
        password TEXT,
        isActive INTEGER DEFAULT 0,
        createdAt TEXT NOT NULL
      )
    `);

    console.log('数据库初始化完成');
  } catch (error) {
    console.error('数据库初始化失败:', error);
  }
};

// 导出数据库实例
export default db; 